package top.likeqc.leetcode.editor.cn;

import java.util.Arrays;

/**
 * @see <a
 *     href="https://leetcode.cn/problems/equal-sum-arrays-with-minimum-number-of-operations">leetcode题库</a>
 */
public class EqualSumArraysWithMinimumNumberOfOperations {
    public static void main(String[] args) {
        Solution solution = new EqualSumArraysWithMinimumNumberOfOperations().new Solution();

        System.out.println(
                solution.minOperations(new int[] {6, 2, 3, 4, 5, 1}, new int[] {1, 1, 2, 2, 2, 2}));
    }
    // leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int minOperations(int[] nums1, int[] nums2) {
            int n = nums1.length, m = nums2.length;
            int sum1 = 0, sum2 = 0;

            sum1 = Arrays.stream(nums1).sum();
            sum2 = Arrays.stream(nums2).sum();

            // [n,6n] 与 [m,6m] 没有重合区间时，返回 -1
            if (6 * n < m || 6 * m < n) {
                return -1;
            }

            int[] cnt = new int[7];
            if (sum1 > sum2) {
                for (int t : nums1) {
                    cnt[t - 1]++;
                }
                for (int t : nums2) {
                    cnt[6 - t]++;
                }

            } else {
                for (int t : nums1) {
                    cnt[6 - t]++;
                }
                for (int t : nums2) {
                    cnt[t - 1]++;
                }
            }
            int dif = Math.abs(sum1 - sum2);
            int ans = 0;
            for (int i = 6; i >= 1; i--) {
                while (cnt[i] > 0) {
                    if (dif < i) {
                        break;
                    }
                    dif -= i;
                    cnt[i]--;
                    ans++;
                }
            }
            ans += dif == 0 ? 0 : 1;
            return ans;
        }
    }
    // leetcode submit region end(Prohibit modification and deletion)

}
